//
//  NetworkManager.swift
//  Xiaozihui
//
//  Created by 校企荟 on 2017/8/21.
//  Copyright © 2017年 校企荟. All rights reserved.
//

import UIKit
import AFNetworking

enum HTTPMethod: Int{
    case GET = 0
    case POST
}


class NetworkManager: NSObject {
    
    var sessionManager : AFHTTPSessionManager?
    
    static let sharedManager:NetworkManager = NetworkManager()
    
    override init() {
        super.init()
        sessionManager = AFHTTPSessionManager(baseURL: URL(string: BaseUrl))
        sessionManager?.requestSerializer.timeoutInterval = 15
//        _manager.responseSerializer.acceptableContentTypes = [NSSet setWithArray:@[@"text/plain",@"application/json",@"text/html"]];
        sessionManager?.responseSerializer.acceptableContentTypes = (NSSet(array: ["text/plain","application/json","text/html"]) as! Set<String>)
        
        
    }
    
    
    func request(method: HTTPMethod, URLString: String, parameters: Any?, finished: @escaping (_ response:Any?, _ error:Error?) -> ()) -> (){
        var dict = parameters as! [String : Any]
        if AccountManager.sharedManager.checkIsLogin() {
            dict["token"] = AccountManager.sharedManager.user?.token
            dict["style"] = AccountManager.sharedManager.user?.style
            dict["id"] = AccountManager.sharedManager.user?.id
        }
        
        
        
        print(dict)
        
        let successClosure = {(dataTask: URLSessionDataTask, response: Any) -> () in
            print(response)
            finished(response,nil)
        }
        
        let failuredClosure = {(dataTask: URLSessionDataTask?, error: Error) -> () in
            print(error)
            finished(nil,error)
        }
        
        switch method {
            
        case .GET:
            
            sessionManager!.get(URLString, parameters: dict, progress: nil, success: successClosure, failure: failuredClosure)
        case .POST:
            sessionManager!.post(URLString, parameters: dict, progress: nil, success: successClosure, failure: failuredClosure)
            
        }
        
    }
    
    
}
